<template>
 <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="设备名称" prop="deviceNickname">
        <el-input
          v-model="queryParams.deviceNickname"
          class="!w-240px"
          clearable
          placeholder="请输入设备名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备Sn" prop="deviceSn">
        <el-input
          v-model="queryParams.deviceSn"
          class="!w-240px"
          clearable
          placeholder="请输入设备Sn"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户名称" prop="merchantId">
      <el-select
        v-model="queryParams.merchantId"
        filterable
        style="width: 240px"
        remote
        reserve-keyword
        placeholder="请选择商户"
        remote-show-suffix
        :remote-method="remoteMethod"
        :loading="merchantLoading"
        
      >
        <el-option
          v-for="item in merchantOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-radio-group v-model="queryParams.status" class="!w-240px">
          <el-radio value="0" size="large">禁用</el-radio>
          <el-radio value="1" size="large">启用</el-radio>
          <el-radio value="2" size="large">故障</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否在线" prop="online">
      <el-radio-group v-model="queryParams.online" class="!w-240px">
        <el-radio value="0" size="large">离线</el-radio>
        <el-radio value="1" size="large">在线</el-radio>
      </el-radio-group>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['product:spu:create']"
          plain
          type="primary"
          @click="dialogAddVisible=true"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          新增
        </el-button>
        <el-button
          v-hasPermi="['product:spu:create']"
          plain
          type="success"
          @click="handleAsync"
        >
          同步所有设备
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
    <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" style="width: 100%">
    <el-table-column align="center" prop="id" label="设备id" min-width="80"  />
    <el-table-column align="center" prop="deviceSn" label="设备Sn" min-width="80"  />
    <el-table-column align="center" prop="merchantName" label="商户名称" min-width="80" />
    <el-table-column align="center" prop="deviceNickname" label="设备名称" />
    <el-table-column align="center" prop="status" label="设备状态" >
      <template #default="scope">
        <el-tag
          :type="equitmentStatusTag[scope.row.status]"
          disable-transitions
          >{{ equitmentStatus[scope.row.status]}}</el-tag
        >
      </template>
    </el-table-column>
    <el-table-column align="center" prop="online" label="是否在线" >
      <template #default="scope">
        <el-tag
          :type="scope.row.online === 1 ? 'success' : 'info'"
          disable-transitions
          >{{ equitmentOnline[scope.row.online]}}</el-tag
        >
      </template>
    </el-table-column>
    <el-table-column align="center" prop="modelName" label="设备类型" />
    <el-table-column align="center" prop="printTimes" label="打印次数" />
    <el-table-column align="center" prop="lastOnlineTime" label="上次在线时间" />
    <el-table-column align="center" prop="createTime" label="创建时间" />
    <el-table-column align="center" prop="updateTime" label="更新时间" />
>
    <el-table-column fixed="right" label="操作" min-width="120">
      <template #default="scope" >
        <el-button link type="success" size="small" @click="handleMatchBind(scope.row)">
          绑定
        </el-button>
        <el-button link type="primary" size="small" @click="handleUpdate(scope.row.id)">修改</el-button>
        <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <Pagination
    v-model:limit="queryParams.pageSize"
    v-model:page="queryParams.pageNo"
    :total="total"
    @pagination="getList"
/>
    <el-dialog v-model="dialogMerchantVisible" title="绑定商户" width="400" >
      <el-select
        v-model="merchantId"
        filterable
        remote
        reserve-keyword
        placeholder="请绑定商户"
        remote-show-suffix
        :remote-method="remoteMethod"
        :loading="merchantLoading"
      >
        <el-option
          v-for="item in merchantOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogMerchantVisible = false">取消</el-button>
        <el-button type="primary" @click="handleBind">
          确认
        </el-button>
      </div>
    </template>
    </el-dialog>
    <el-dialog v-model="dialogAddVisible" title="新增设备" width="400" >
      <AddEquitment @refresh="handleQuery"
      @close="dialogAddVisible = false"  />
    </el-dialog>
    <el-dialog v-model="dialogtUpdateVisible" title="修改设备" width="400" >
      <UpdateEquitment  :id="equitmentId"  @refresh="handleQuery"   @close="dialogtUpdateVisible = false"  />
    </el-dialog>
  </ContentWrap>
</template>

<script lang="ts" setup>

defineOptions({ name: 'equitment' })
interface MerchantItem {
  value: string
  label: string
}
interface MerchanVo {
  id: string
  name: string
}
import * as EquitmentApi from '@/api/mall/equitment/manager'
import * as MerchantAPi from '@/api/mall/merchant/index'
import {AddEquitment,UpdateEquitment} from './component/index'

const message = useMessage() // 消息弹窗
const route = useRoute() // 路由
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转
const dialogMerchantVisible = ref(false)
const dialogAddVisible = ref(false)
const dialogtUpdateVisible = ref(false)
const loading = ref(false) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 
const merchantId=ref('')
const deviceSn=ref('')
const equitmentId=ref(0)
const merchantLoading=ref(false)
const merchantOptions = ref<MerchantItem[]>([])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  merchantId: "" ,// 商户
  deviceSn: "" ,// 设备Sn
  deviceNickname: "" ,// 设备名称
  modelType:0 ,// 设备类型
  status:undefined ,// 设备状态 本地状态 0-禁用 1-启用 2-故障
  online:undefined ,// 设备是否在线 0-离线 1-在线
  createTime: undefined
}) // 查询参数
const queryFormRef = ref() // 搜索的表单Ref
const equitmentStatusTag={
  0: "waring",
  1: "success",
  2: "danger"
}
const equitmentStatus={
  0: "禁用",
  1: "启用",
  2: "故障"
}
const equitmentOnline={
  0: "离线",
  1: "在线"
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await EquitmentApi.getEquitmentPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  if(queryFormRef.value){
    queryFormRef.value.resetFields()
  }
  handleQuery()
}

const remoteMethod = (query: string) => {
  if (query) {
    merchantLoading.value = true
    MerchantAPi.getMerchantPage({
      pageNo: 1,
      pageSize: 10,
      name: query,
    }).then((res)=>{
      merchantLoading.value = false
      merchantOptions.value = res.list.filter((item:MerchanVo) => {
        return item.name.toLowerCase().includes(query.toLowerCase())
      }).map((item:MerchanVo)=>{
        return {
          value: item.id,
          label: item.name
        }
      })
    }).catch((err)=>{
      merchantLoading.value = false
      merchantOptions.value = []
    })

  } else {
    merchantOptions.value = []
  }
}
const handleMatchBind=(row:any)=>{
  dialogMerchantVisible.value = true;
  deviceSn.value=row.deviceSn
  merchantId.value=row.merchantId
  merchantOptions.value=[{
    value:row.merchantId,
    label:row.merchantName
  }]
}

const handleBind = () => {
  dialogMerchantVisible.value = false
    EquitmentApi.equitmentToShop({deviceSn:deviceSn.value,merchantId:merchantId.value}).then(res=>{
      if(res){
        message.success("绑定成功")
        handleQuery()
        merchantOptions.value=[]
        merchantId.value=''
        deviceSn.value=''
      }
    }).catch(err=>{
      message.error(err.message)
    }).finally(()=>{
      dialogMerchantVisible.value = false
    })
  message.success("绑定成功")
}
const handleUpdate=( id:number)=>{
  equitmentId.value=id;
    dialogtUpdateVisible.value = true;
}
const handleDelete=(id:number)=>{
     EquitmentApi.deleteEquitment(id).then(()=>{
         message.success("删除成功")
         getList()
     }).catch((err)=>{
         message.error(err.message)
     })
}
const handleAsync=()=>{
  EquitmentApi.matchEquitments().then(()=>{
    message.success("同步成功")
    getList()
  }).catch((err)=>{
    message.error(err.message)
  })
}
/** 初始化 **/
onMounted(async () => {
  // 获得商品信息
  await getList()
})
</script>